// src/screens/FilterScreen.js
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, ScrollView, Switch, Alert, PermissionsAndroid, Platform, Linking } from 'react-native';
import { useSelector } from 'react-redux';
import Geolocation from 'react-native-geolocation-service';
import api from '../services/api';
import { getLocationServiceForCoordinates, isLikelyInChina } from '../utils/locationService';

const FilterScreen = ({ navigation, route }) => {
  const userInfo = useSelector(state => state.user.userInfo);
  
  // 初始化过滤器状态
  const [filters, setFilters] = useState({
    location: {
      latitude: 0,
      longitude: 0,
      address: '点击获取当前位置',
      roaming: false,
      country: '',
      province: '',
      city: '',
      district: ''
    },
    gender: '',
    ageRange: {
      min: 18,
      max: 35
    },
    languages: [],
    nationality: '',
    hideSameNationality: false,
    excludedNationalities: []
  });

  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // 获取当前用户的筛选条件
    fetchFilters();
  }, []);

  const fetchFilters = async () => {
    try {
      const response = await api.getFilters();
      if (response.success) {
        setFilters({
          ...response.data
        });
      }
    } catch (error) {
      console.log('获取筛选条件失败:', error);
    }
  };

  const saveFilters = async () => {
    setLoading(true);
    try {
      const response = await api.saveFilters(filters);
      if (response.success) {
        Alert.alert('提示', '筛选条件保存成功');
        navigation.goBack();
      } else {
        Alert.alert('错误', response.message || '保存失败');
      }
    } catch (error) {
      console.log('保存筛选条件时出错:', error);
      Alert.alert('错误', '保存失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const updateLocation = (field, value) => {
    setFilters({
      ...filters,
      location: {
        ...filters.location,
        [field]: value
      }
    });
  };

  const updateAgeRange = (field, value) => {
    setFilters({
      ...filters,
      ageRange: {
        ...filters.ageRange,
        [field]: parseInt(value) || 0
      }
    });
  };

  const toggleHideSameNationality = () => {
    setFilters({
      ...filters,
      hideSameNationality: !filters.hideSameNationality
    });
  };

  const requestLocationPermission = async () => {
    if (Platform.OS === 'android') {
      try {
        // 先检查是否已有权限
        const checkResult = await PermissionsAndroid.check(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
        );

        if (checkResult) {
          console.log('已经有位置权限');
          return true;
        }

        // 如果没有权限，则请求权限
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
            title: 'Face to Face位置权限',
            message: 'Face to Face需要访问您的位置信息来确定您所在的国家',
            buttonNeutral: '稍后询问',
            buttonNegative: '取消',
            buttonPositive: '确定',
          },
        );

        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('位置权限已授予');
          return true;
        } else {
          console.log('位置权限被拒绝或未授予');
          Alert.alert(
            '权限需要',
            '需要位置权限才能获取当前位置，请在设置中开启位置权限',
            [
              { text: '取消', style: 'cancel' },
              { text: '去设置', onPress: () => Linking.openSettings() }
            ]
          );
          return false;
        }
      } catch (err) {
        console.warn('请求位置权限时出错:', err);
        Alert.alert('错误', '请求位置权限时发生错误，请手动在设置中开启');
        return false;
      }
    } else if (Platform.OS === 'ios') {
      // iOS特殊处理
      try {
        const checkResult = await Geolocation.requestAuthorization('whenInUse');
        if (checkResult === 'granted') {
          return true;
        } else {
          Alert.alert(
            '权限受限',
            '位置权限受限，请在设置中开启位置权限',
            [
              { text: '取消', style: 'cancel' },
              { text: '去设置', onPress: () => Linking.openSettings() }
            ]
          );
          return false;
        }
      } catch (err) {
        console.warn('请求iOS位置权限时出错:', err);
        Alert.alert(
          '错误',
          '请求位置权限时发生错误，请检查设备设置',
          [
            { text: '取消', style: 'cancel' },
            { text: '去设置', onPress: () => Linking.openSettings() }
          ]
        );
        return false;
      }
    }
    return true; // 默认情况
  };

  const getCurrentLocation = async () => {
    try {
      const hasPermission = await requestLocationPermission();
      if (!hasPermission) {
        return;
      }

      Geolocation.getCurrentPosition(
        (position) => {
          try {
            const { latitude, longitude } = position.coords;
            
            // Determine which location service to use
            const locationService = getLocationServiceForCoordinates(latitude, longitude);
            const useAMap = (locationService === 'AMap');
            
            if (useAMap) {
              // 使用高德地图API获取详细地址信息
              fetch(`https://restapi.amap.com/v3/geocode/regeo?key=a505badf96455e4fca2062182129b0e5&location=${longitude},${latitude}&output=json`)
                .then(response => {
                  console.log('高德地图API响应状态:', response.status);
                  return response.json();
                })
                .then((data) => {
                  // 处理高德地图API返回的数据
                  handleAMapResponse(data, latitude, longitude);
                })
                .catch(err => {
                  console.log('获取详细地址失败:', err);
                  // 出错时仍然显示经纬度
                  handleLocationError(latitude, longitude, 'amap');
                });
            } else {
              // 使用Google Geocoding API获取详细地址信息
              // 注意：这里需要配置Google Cloud Platform并获取API密钥
              // 为了演示，我们暂时使用占位符
              const googleApiKey = 'YOUR_GOOGLE_API_KEY'; // 需要在Google Cloud Platform中配置
              
              fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${googleApiKey}`)
                .then(response => {
                  console.log('Google Geocoding API响应状态:', response.status);
                  return response.json();
                })
                .then((data) => {
                  // 处理Google Geocoding API返回的数据
                  handleGoogleResponse(data, latitude, longitude);
                })
                .catch(err => {
                  console.log('获取详细地址失败:', err);
                  // 出错时仍然显示经纬度
                  handleLocationError(latitude, longitude, 'google');
                });
            }
          } catch (stateError) {
            console.log('更新位置状态出错:', stateError);
            Alert.alert('错误', '位置获取成功但更新界面时出错');
          }
        },
        (error) => {
          console.log('获取位置信息失败:', error);
          let errorMessage = '无法获取当前位置，请确保已开启定位服务';

          if (error.code) {
            switch (error.code) {
              case 1:
                errorMessage = '位置权限被拒绝，请在设置中开启位置权限';
                break;
              case 2:
                errorMessage = '位置信息不可用，请检查GPS是否开启';
                break;
              case 3:
                errorMessage = '获取位置信息超时，请稍后再试';
                break;
              default:
                errorMessage = `获取位置失败: ${error.message || '未知错误'}`;
            }
          }

          Alert.alert('获取位置失败', errorMessage);
        },
        {
          enableHighAccuracy: false,
          timeout: 10000,
          maximumAge: 60000,
          forceRequestLocation: true
        }
      );
    } catch (error) {
      console.log('请求位置过程中出错:', error);
      Alert.alert('错误', '请求位置时发生意外错误');
    }
  };

  // 处理高德地图API响应
  const handleAMapResponse = async (data, latitude, longitude) => {
    console.log('高德地图API返回数据:', data);
    if (data.status === '1' && data.regeocode) {
      const addressComponent = data.regeocode.addressComponent;
      console.log('地址组件:', addressComponent);

      const { country, province, city, district } = addressComponent;

      // 更新位置信息
      const newLocation = {
        latitude,
        longitude,
        country: country || '',
        province: province || '',
        city: city || '',
        district: district || '',
        address: `${country || ''}${province ? ', ' + province : ''}${city ? ', ' + city : ''}`
      };
      
      setFilters({
        ...filters,
        location: {
          ...filters.location,
          ...newLocation
        }
      });

      // 更新服务器上的用户位置信息
      try {
        await api.updateUserLocation({
          latitude,
          longitude,
          location: `${country || ''}${province ? ', ' + province : ''}${city ? ', ' + city : ''}`,
          locationDetails: {
            country: country || '',
            province: province || '',
            city: city || '',
            district: district || '',
            source: 'amap'
          }
        });
      } catch (error) {
        console.log('更新服务器位置信息失败:', error);
      }

      Alert.alert('位置获取成功', `${country || ''}${province ? ', ' + province : ''}${city ? ', ' + city : ''}`);
    } else {
      console.log('高德地图API返回错误或无结果');
      // 如果无法获取详细地址，则仍然显示经纬度
      handleLocationError(latitude, longitude, 'amap');
    }
  };

  // 处理Google Geocoding API响应
  const handleGoogleResponse = async (data, latitude, longitude) => {
    console.log('Google Geocoding API返回数据:', data);
    if (data.status === 'OK' && data.results.length > 0) {
      const result = data.results[0];
      const addressComponents = result.address_components;
      
      // 提取地址组件
      let country = '';
      let province = '';
      let city = '';
      let district = '';
      
      addressComponents.forEach(component => {
        if (component.types.includes('country')) {
          country = component.long_name;
        }
        if (component.types.includes('administrative_area_level_1')) {
          province = component.long_name;
        }
        if (component.types.includes('locality')) {
          city = component.long_name;
        }
        if (component.types.includes('sublocality')) {
          district = component.long_name;
        }
      });

      // 更新位置信息
      const newLocation = {
        latitude,
        longitude,
        country: country || '',
        province: province || '',
        city: city || '',
        district: district || '',
        address: `${country || ''}${province ? ', ' + province : ''}${city ? ', ' + city : ''}`
      };
      
      setFilters({
        ...filters,
        location: {
          ...filters.location,
          ...newLocation
        }
      });

      // 更新服务器上的用户位置信息
      try {
        await api.updateUserLocation({
          latitude,
          longitude,
          location: `${country || ''}${province ? ', ' + province : ''}${city ? ', ' + city : ''}`,
          locationDetails: {
            country: country || '',
            province: province || '',
            city: city || '',
            district: district || '',
            source: 'google'
          }
        });
      } catch (error) {
        console.log('更新服务器位置信息失败:', error);
      }

      Alert.alert('Location acquired successfully', `${country || ''}${province ? ', ' + province : ''}${city ? ', ' + city : ''}`);
    } else {
      console.log('Google Geocoding API返回错误或无结果');
      // 如果无法获取详细地址，则仍然显示经纬度
      handleLocationError(latitude, longitude, 'google');
    }
  };

  // 处理位置获取错误的情况
  const handleLocationError = async (latitude, longitude, source) => {
    const isChinese = source === 'amap';
    const newLocation = {
      latitude,
      longitude,
      address: isChinese 
        ? `纬度: ${latitude.toFixed(4)}, 经度: ${longitude.toFixed(4)}` 
        : `Lat: ${latitude.toFixed(4)}, Lng: ${longitude.toFixed(4)}`
    };
    
    setFilters({
      ...filters,
      location: {
        ...filters.location,
        ...newLocation
      }
    });

    // 更新服务器上的用户位置信息
    try {
      await api.updateUserLocation({
        latitude,
        longitude,
        location: isChinese 
          ? `纬度: ${latitude.toFixed(4)}, 经度: ${longitude.toFixed(4)}` 
          : `Lat: ${latitude.toFixed(4)}, Lng: ${longitude.toFixed(4)}`,
        locationDetails: {
          source: source
        }
      });
    } catch (error) {
      console.log('更新服务器位置信息失败:', error);
    }

    Alert.alert(
      '位置获取成功', 
      isChinese 
        ? `纬度: ${latitude.toFixed(4)}, 经度: ${longitude.toFixed(4)}` 
        : `Lat: ${latitude.toFixed(4)}, Lng: ${longitude.toFixed(4)}`
    );
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <Text style={styles.backButton}>返回</Text>
        </TouchableOpacity>
        <Text style={styles.title}>筛选条件</Text>
        <TouchableOpacity onPress={saveFilters} disabled={loading}>
          <Text style={[styles.saveButton, loading && styles.disabledButton]}>
            {loading ? '保存中...' : '保存'}
          </Text>
        </TouchableOpacity>
      </View>

      {/* 位置设置 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>位置设置</Text>

        <TouchableOpacity
          style={styles.locationContainer}
          onPress={getCurrentLocation}
        >
          <Text style={styles.locationText}>
            {filters.location.country || filters.location.province || filters.location.city ?
              `${filters.location.country || ''}${filters.location.province ? ', ' + filters.location.province : ''}${filters.location.city ? ', ' + filters.location.city : ''}` :
              filters.location.address}
          </Text>
        </TouchableOpacity>
        
        <View style={styles.row}>
          <Text style={styles.label}>启用漫游:</Text>
          <Switch
            value={filters.location.roaming}
            onValueChange={(value) => updateLocation('roaming', value)}
          />
        </View>
      </View>

      {/* 性别筛选 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>朋友性别</Text>
        
        <View style={styles.optionsContainer}>
          {['男性', '女性', '不限'].map((gender) => (
            <TouchableOpacity
              key={gender}
              style={[
                styles.optionButton,
                filters.gender === gender && styles.selectedOption
              ]}
              onPress={() => setFilters({...filters, gender})}
            >
              <Text style={[
                styles.optionText,
                filters.gender === gender && styles.selectedOptionText
              ]}>
                {gender}
              </Text>
            </TouchableOpacity>
          ))}
        </View>
      </View>

      {/* 年龄范围 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>朋友年龄</Text>
        
        <View style={styles.row}>
          <Text style={styles.label}>最小年龄:</Text>
          <TextInput
            style={styles.input}
            value={filters.ageRange.min.toString()}
            onChangeText={(value) => updateAgeRange('min', value)}
            keyboardType="numeric"
          />
        </View>
        
        <View style={styles.row}>
          <Text style={styles.label}>最大年龄:</Text>
          <TextInput
            style={styles.input}
            value={filters.ageRange.max.toString()}
            onChangeText={(value) => updateAgeRange('max', value)}
            keyboardType="numeric"
          />
        </View>
      </View>

      {/* 语言偏好 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>感兴趣的语言</Text>
        <TextInput
          style={[styles.input, styles.multilineInput]}
          value={filters.languages.join(', ')}
          onChangeText={(text) => setFilters({
            ...filters,
            languages: text.split(',').map(item => item.trim()).filter(item => item)
          })}
          placeholder="输入语言，用逗号分隔"
          multiline
        />
      </View>

      {/* 国籍设置 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>朋友国籍</Text>
        <TextInput
          style={styles.input}
          value={filters.nationality}
          onChangeText={(text) => setFilters({...filters, nationality: text})}
          placeholder="输入国籍"
        />
      </View>

      {/* 隐藏同国籍 */}
      <View style={styles.section}>
        <View style={styles.row}>
          <Text style={styles.label}>不显示同国籍的朋友:</Text>
          <Switch
            value={filters.hideSameNationality}
            onValueChange={toggleHideSameNationality}
          />
        </View>
      </View>

      {/* 排除的国籍 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>排除的国籍</Text>
        <TextInput
          style={[styles.input, styles.multilineInput]}
          value={filters.excludedNationalities.join(', ')}
          onChangeText={(text) => setFilters({
            ...filters,
            excludedNationalities: text.split(',').map(item => item.trim()).filter(item => item)
          })}
          placeholder="输入要排除的国籍，用逗号分隔"
          multiline
        />
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5'
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
    backgroundColor: '#2196F3',
  },
  backButton: {
    color: 'white',
    fontSize: 16,
  },
  title: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
  saveButton: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  disabledButton: {
    opacity: 0.6,
  },
  section: {
    backgroundColor: 'white',
    padding: 15,
    marginVertical: 5,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#333',
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 10,
  },
  label: {
    fontSize: 16,
    color: '#666',
    flex: 1,
  },
  locationContainer: {
    backgroundColor: '#f0f0f0',
    padding: 15,
    borderRadius: 5,
    marginBottom: 10,
  },
  locationText: {
    fontSize: 16,
    color: '#333',
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 10,
    backgroundColor: 'white',
    flex: 2,
  },
  multilineInput: {
    height: 80,
    textAlignVertical: 'top',
  },
  optionsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  optionButton: {
    flex: 1,
    padding: 10,
    marginHorizontal: 5,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    alignItems: 'center',
  },
  selectedOption: {
    backgroundColor: '#2196F3',
    borderColor: '#2196F3',
  },
  optionText: {
    color: '#666',
  },
  selectedOptionText: {
    color: 'white',
  },
});

export default FilterScreen;